<script setup lang="ts">
import { flattenAreaData, type Area } from '@/utils/area'
import { showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { computed, onMounted, ref } from 'vue'
import b64toBlob from 'b64-to-blob'
import { request } from '@/api'

// 保存信息
const loading = ref(false)
const onSubmit = async () => {
  console.log(profile.value)
  // mk.vibrator()
  loading.value = true
  const res = await request.put('member/profile', profile.value)
  loading.value = false
  mk.updateUser(res.data.result)
  showToast({ message: '保存成功' })
}

// 选择修改头像
const showAvatarSheet = ref(false)
const onSelectAvatar = async (item: ActionSheetAction, i: number) => {
  if (i === 0) {
    const b64Str = await mk.pickerCamera()
    uploadImg(b64Str)
    showAvatarSheet.value = false
  } else if (i === 1) {
    const b64Str = await mk.pickerPhoto()
    uploadImg(b64Str)
  }
}
const uploadImg = async (str: string) => {
  // 上传头像逻辑
  const file = b64toBlob(str, 'image/jpeg')
  const fd = new FormData()
  fd.append('file', file, Date.now + '.jpeg')

  showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
  const res = await request.post('member/profile/avatar', fd)
  profile.value.avatar = res.data.result.avatar
  showToast('上传成功')
}

// 日期选择返回参数类型
interface IPickerParams {
  selectedValues: string[]
  selectedOptions: {
    text: string
    value: string
  }[]
  selectedIndexes: number[]
}

// 选择生日
const showBirthdayPopup = ref(false)
const onChangeBirthday = ({ selectedValues }: IPickerParams) => {
  profile.value.birthday = selectedValues.join('-')
  showBirthdayPopup.value = false
}

// 选择所在地
const isShowArea = ref(false)
const columns = ref<Area[]>([])
console.log(columns.value)

const str = mk.getAreaColumns()
columns.value = JSON.parse(str)
const res = flattenAreaData(JSON.parse(str))

const onSelectArea = (data: IPickerParams) => {
  const pName = res[data.selectedValues[0]]
  const cName = res[data.selectedValues[1]]
  const aName = res[data.selectedValues[2]]

  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]

  profile.value.fullLocation = `${pName}${cName}${aName}`
  isShowArea.value = false
}

// 4. 选择职业
const columnsPro = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues[0]
}

const birthList = computed(() => {
  return profile.value.birthday.split('-')
})

const profile = ref({} as HDMUser)
onMounted(() => {
  profile.value = mk.queryUser()
})
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        readonly
        placeholder="请选择日期"
        @click="showBirthdayPopup = true"
        v-model="profile.birthday"
      ></van-field>

      <van-field
        label="所在地"
        readonly
        placeholder="请选择所在地"
        @click="isShowArea = true"
        v-model="profile.fullLocation"
      ></van-field>
      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        @click="showProfessionPopup = true"
        v-model="profile.profession"
      ></van-field>
    </van-cell-group>

    <div class="submit" @click="onSubmit">
      <van-button round block type="primary"> 保存资料 </van-button>
    </div>
  </div>

  <!-- 相册弹出层 -->
  <van-action-sheet
    v-model:show="showAvatarSheet"
    :actions="[{ name: '相册' }, { name: '拍照' }]"
    @select="onSelectAvatar"
    cancel-text="取消"
    :style="{ paddingBottom: '20px' }"
  ></van-action-sheet>

  <!-- 选择生日弹出 -->
  <van-popup v-model:show="showBirthdayPopup" round position="bottom">
    <van-date-picker
      title="选择生日"
      :model-value="birthList"
      @cancel="showBirthdayPopup = false"
      @confirm="onChangeBirthday"
      :min-date="new Date('1980-01-01')"
      :max-date="new Date()"
    />
  </van-popup>

  <!-- 选择所在地 -->
  <van-popup v-model:show="isShowArea" position="bottom">
    <van-picker
      :columns-field-names="{ text: 'name', value: 'code', children: 'areaList' }"
      title="选择地址"
      :columns="columns"
      @cancel="isShowArea = false"
      @confirm="onSelectArea"
    >
    </van-picker>
  </van-popup>

  <!-- 打开选择职业弹层 -->
  <van-popup v-model:show="showProfessionPopup" round position="bottom">
    <van-picker
      :columns="columnsPro"
      @confirm="onChangeProfession"
      @cancel="showProfessionPopup = false"
    />
  </van-popup>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
